
import {isObject,extend} from "../base";

export default function(url, config) {

    return new Promise(function(resolve, reject){
        if (isObject(url)) {
            config = extend(url);
        } else {
            config = extend(config);
            config.url = url;
        }

        var xmlRequest = undefined;

        if (typeof XMLHttpRequest != 'undefined') {
            xmlRequest = new XMLHttpRequest();
        } else {
            xmlRequest = new ActiveXObject('Microsoft.XMLHTTP');
        }

        config.method = config.method || 'get';
        var body = config.body || {};

        config.contentType = config.contentType || 'application/x-www-form-urlencoded';


        // xmlRequest.open(config.method, config.url, config.async || true, config.bstrUser, config.bstrPassword);
        xmlRequest.open(config.method, config.url, config.async);
        if (config.async) {
            xmlRequest.timeout = config.timeout || 20 * 1000;
        }
        if (typeof body !== 'FormData') { //文件上传时，不能设置 Content-Type
            xmlRequest.setRequestHeader('Content-Type', config.contentType);
        }

        for (var header in config.headers) {
            xmlRequest.setRequestHeader(header, config.headers[header]);
        }

        xmlRequest.send(body);

        var onreadystatechange = function() {

            if (xmlRequest.readyState == 3) {
                // progress();
                return;
            }
            if (xmlRequest.readyState != 4) {
                return;
            }

            //处理响应头信息
            var headers = {};
            var rheaders = xmlRequest.getAllResponseHeaders().split('\n');
            for(var n = 0; n<rheaders.length;n++){
                var item = rheaders[n];
                var h = item.match(/((?!:).)*(?:)/g)[0];
                if(!h){
                    continue;
                }
                headers[h] = xmlRequest.getResponseHeader(h);
            }

            resolve({
                text: xmlRequest.responseXML || xmlRequest.responseText,
                status:xmlRequest.status,
                statusText:xmlRequest.statusText,
                timeout:xmlRequest.timeout,
                headers:headers,
            });

        };

        xmlRequest.ontimeout = function (e) {
            // XMLHttpRequest 超时。在此做某事。
            console.log('=== time out ====')
        };
        if (config.async == true) {
            xmlRequest.onreadystatechange = onreadystatechange;
        } else {
            onreadystatechange();
        }
    });
}




